package com.ckzp.weixin.game;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.util.DateUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.plugins.UpImage;
import com.jfinal.kit.HttpKit;

import java.util.Date;
import java.util.Map;

/**
 * Created by 51594 on 2023/10/9.
 */
public class WxGameTool {

    //小程序
    private static String APP_ACCESS_TOKEN;
    private static Date APP_LOAD_DATE = new Date();


    /**
     * 取小程序
     *
     * @return
     */
    public static String getAccessToken() {
        if (APP_ACCESS_TOKEN == null || APP_ACCESS_TOKEN.length() < 10 || (new Date().after(DateUtil.getAddDate(APP_LOAD_DATE, (long) (60 * 60 * 1000))))) {
            return LoadAccessToken();
        } else {
            return APP_ACCESS_TOKEN;
        }
    }

    /**
     * @return
     */
    public static String LoadAccessToken() {
        String APPID = WxGameTool.getAppID();
        String SECRET = WxGameTool.getAppToken();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
        String htmls = HttpKit.get(url);
//        System.out.println(htmls);
        Map m = JSON.parseObject(htmls, Map.class);
        if (m != null) {
            String access_token = StringUtil.getString(m, "access_token");
            APP_ACCESS_TOKEN = access_token;
            APP_LOAD_DATE = new Date();
            return access_token;
        }
        return null;
    }


    /**
     * @return
     */
    public static String getAppID() {
        return ConfigUtil.getProperty("WXGAME_APPID");
    }


    /**
     * @return
     */
    public static String getAppToken() {
        return ConfigUtil.getProperty("WXGAME_TOKEN");
    }

    /**
     * 根据code 换取openid和session_key
     *
     * @param code
     * @return
     */
    public static Results getGameOpenIdAndSessionKey(String code) {
        Results results = Results.n(9).setMsg("获取信息失败");
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + getAppID() + "&secret=" + getAppToken() + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            JSONObject result = JSONUtil.parseObj(HttpKit.get(url).toString());
            if (result == null) return results.setMessage("result null");
            Integer errcode = result.getInt("errcode");
            if (errcode == null) {
                results.setCode(0).setMsg("成功")
                        .addData("openid", result.getStr("openid", ""))
                        .addData("session_key", result.getStr("session_key", ""))
                        .addData("unionid", result.getStr("unionid", ""))
                ;
            } else {
                results.setCode(errcode).setMessage(result.getStr("errmsg"));
            }
        } catch (Exception e) {
            results.setMessage(e.getMessage());
        }
//        System.out.println(results.toJson());
        return results;
    }

    /**
     * 取得小游戏二维码
     *
     * @param path
     * @param scene
     * @param env
     * @return
     */
    public static Results getGameQrCode(String path, String scene, int env) {
        return getBaseGameQrCode(path, Jmode.n().set("page", "page/index/index")
                .set("width", 280)
                .set("scene", scene)
                .set("check_path", false)
                .set("env_version", env == 1 ? "release" : env == 2 ? "trial" : "develop")
                .toJson());
    }

    /**
     * 取得小游戏二维码
     *
     * @param path 文件保存路经
     * @param body
     * @return
     */
    public static Results getBaseGameQrCode(String path, String body) {
        Results results = Results.n();
        HttpResponse rsp = HttpRequest.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + getAccessToken())
                .body(body)
                .execute();
        String bodys = rsp.body();
        if (bodys.indexOf("errcode") > -1) {
            results.setCode(9).setMsg("获取二维码失败").setMessage(bodys);
        } else {
            IoUtil.write(FileUtil.getOutputStream(UpImage.IMAGE_SAVE_PATH + path), true, rsp.bodyBytes());
        }
        return results.setCode(0).setMsg("成功").addData("view_path", UpImage.TransUrl(path));
    }


    public static void main(String[] arg) {
        // String token = WxGameTool.getAccessToken();
        // System.out.println(token);
        WxGameTool.getBaseGameQrCode("d:/4.png", "dd");
    }
}
